package com.example.ssedemo;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class SSEController {

    private Map<String, SseEmitter> emMap = new HashMap<>();

    @RequestMapping(path = "/getMessage", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream(String id) {
        SseEmitter emitter = new SseEmitter();
        emMap.put(id, emitter);
        emitter.onCompletion(() -> emMap.remove(id));
        return emitter;
    }

    @GetMapping(path = "/sendMessage")
    public String sendMessage(String message, String id) {
        SseEmitter emitter = emMap.get(id);
        if (emitter == null) {
            return "还未注册SSE";
        }
        try {
            emitter.send(new User("测试用户名", 11, message), MediaType.APPLICATION_JSON);
        } catch (IOException e) {
            emitter.complete();
            emMap.remove(id);
            e.printStackTrace();
        }
        return message;
}

}
